package com.zhj.interview;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author zhj
 */
public class Test28 {
    private static ReentrantLock lock = new ReentrantLock();

    public static void main(String[] args) {
        Thread t1 = new Thread(()->{
            System.out.println("t1 尝试获取锁");
            try {
                if (! lock.tryLock(1, TimeUnit.SECONDS)) {
                    System.out.println("t1 获取不到锁");
                    return;
                }
                try {
                    System.out.println("t1 获得到锁");
                } finally {
                    lock.unlock();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"t1");
        System.out.println("主线程添加了锁");
        lock.lock();
        t1.start();
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        lock.unlock();
        System.out.println("主线程释放了锁");

        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
